<template>
  <div class="order-channel-container-101">
    <Header
      v-if="currentShowInfo"
      :info="currentShowInfo"
      :selectedSeat="selectedSeat"
      :arealist="arealist"
    >
    </Header>
    <!-- 预报价 start -->
    <div class="channel-title">请选择主备渠道(主渠道提交失败后走备选渠道)</div>

    <Chaneel
      :rateList="rateList"
      :isShowPrice="isShowPrice"
      :arealist="arealist"
      :tabList="chanelList"
      :currentShowInfo="currentShowInfo"
      :selectedSeat="selectedSeat ? selectedSeat : []"
      :selectedChannelList="selectedChannelList"
      @onSelectedChannel="getSelectedChannel"
      :requestTime="requestTime"
      :screenHeight="screenHeight"
      :screenWidth="screenWidth"
    ></Chaneel>
    <!-- 预报价 end -->
    <div class="set-seat-box">
      <div class="title">
        <div class="text">是否调座位</div>
        <IconFont @click="seatImageShow = true" name="ask" size="14"></IconFont>
      </div>
      <div class="value">
        <nut-radio-group
          v-model="checkedSeat"
          @change="handleChangeRadio"
          direction="horizontal"
        >
          <nut-radio label="1"
            >九宫格调座
            <template #icon>
              <IconFont name="check-normal"></IconFont>
            </template>
            <template #checkedIcon>
              <IconFont name="checked" color="#5232b7"></IconFont></template
          ></nut-radio>
          <nut-radio label="0"
            >不可调座<template #icon>
              <IconFont name="check-normal"></IconFont>
            </template>
            <template #checkedIcon>
              <IconFont name="checked" color="#5232b7"></IconFont></template
          ></nut-radio>
        </nut-radio-group>
      </div>
    </div>
    <div class="limit-prcie-box" v-if="matchChannelFailstate">
      <div class="left">
        <div class="title">单张影票限价</div>
        <div class="desc">限价是根据目前市场上的的价格自动推荐</div>
      </div>
      <div class="right">
        <div class="box" @click="handleClickPrice">
          <div class="price">￥{{ changeTwoDecimal(priList.Price) }}</div>
          <div class="rate">({{ priList.name }})</div>
        </div>
      </div>
    </div>

    <!-- 底部footer -->
    <!-- :radioVal="radioVal" -->

    <Footer
      v-if="currentShowId"
      :selectedSeat="selectedSeat"
      :currentShowId="currentShowId"
      :matchChannelFailstate="matchChannelFailstate"
      :inputLimitPrice="priList"
      :Price="totalPriceNum / selectedSeat.length"
      :checkedSeat="checkedSeat"
      :arealist="arealist"
      :rateList="rateList"
      :radioValList="selectedChannelList"
      :requestTime="requestTime"
      @onCancelTime="onCancelTimeFun"
    >
    </Footer>
    <!-- 底部footer -->
    <!-- 显示限价的弹框 -->
    <nut-dialog
      v-model:visible="limitPriceShow"
      position="center"
      :close-on-click-overlay="true"
      title="限价"
      round
    >
      <PriceLimit
        ref="PriceLimitRef"
        :info="selectedSeat ? selectedSeat : []"
        :arealist="arealist"
        :Price="totalPriceNum / selectedSeat.length"
        :rateList="rateList"
        :isShowPrice="isShowPrice"
        :screenHeight="screenHeight"
        :screenWidth="screenWidth"
        :selectedChannelList="selectedChannelList"
      ></PriceLimit>
      <template v-slot:footer>
        <nut-row :gutter="10">
          <nut-col :span="12">
            <div class="flex-content">
              <nut-button
                type="default"
                size="small"
                @click="
                  () => {
                    limitPriceShow = false;
                  }
                "
                >取消</nut-button
              >
            </div>
          </nut-col>
          <nut-col :span="12">
            <div class="flex-content flex-content-light">
              <nut-button
                size="small"
                color="linear-gradient(to right, #5232B7,#7237BC)"
                @click="handleClickConfirm"
                >确定</nut-button
              >
            </div>
          </nut-col>
        </nut-row>
      </template>
    </nut-dialog>
    <!-- 显示九宫格的图片样式 的弹窗 -->
    <nut-popup
      v-model:visible="seatImageShow"
      position="center"
      round
      closeable
    >
      <div style="margin: 40px">
        <image
          src="../../assets/images/jiu.png"
          style="width: 250px; height: 420px"
        ></image>
      </div>
    </nut-popup>
  </div>
</template>
<script setup>
import Taro from "@tarojs/taro";
import { ref, computed, onMounted, watch, onBeforeUnmount } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import * as PirceApi from "../../api/price";
import { timerFun, destroyTime } from "../../utils/timing";
import Header from "./header";
import Chaneel from "./channel.vue";
import Footer from "./footer.vue";
import PriceLimit from "./price-limit.vue";
const checkedSeat = ref("1"); //选座为标识
const router = Taro.useRouter(); //路由
const seatImageShow = ref(false); //九宫格 图片调座位
const limitPriceShow = ref(false); //限价弹框
const limitPrice = ref(0); //限价弹框
//监听当前的倒计时
const requestTime = ref(40); //倒计时
const requestNum = ref(0);
watch(
  requestTime,
  (newVal, oldVal) => {
    if (newVal == 0) {
      chanelList.value = chanelList.value.sort(
        (a, b) => a.netPrice - b.netPrice
      );
      Taro.hideLoading();
      destroyTime(); //消除定时器
    }
  },
  { deep: true }
); // 由于我们要监听数组内部的变化，所以需要设置 deep: true3
//选择 当前选座的Radio
const handleChangeRadio = (e) => {
  checkedSeat.value = e;
};
//将当前的时间变为0
const onCancelTimeFun = () => {
  requestTime.value = 0;
  remainingTime.value = 0;
};
const limitPriceInfo = ref({
  //限价的参数
  name: 0,
  zhe: 0,
  id: "",
});
const PriceLimitRef = ref(null); //当前 限价的弹框里
//监听请求倒计时的h时间
//四舍五人
const changeTwoDecimal = (x) => {
  let resNum = parseFloat(x);
  // isNaN()，判断一个变量是否为非数字的类型，非数字返回true，数字则返回false
  // console.log('你看=', isNaN(resNum))
  if (isNaN(resNum)) {
    return false;
  }
  resNum = Math.round(resNum * 100) / 100;
  return resNum;
};
const isShowPrice = ref(1); //渠道选择
//计算当前的最大的数值
const findMaxNetPriceItem = (items) => {
  let minItem = null;
  let minNetPrice = Infinity; // 初始化为正无穷大，以便找到更小的值
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.isSupport === 1) {
      let currentNetPrice = parseFloat(item.netPrice);
      // 检查 currentNetPrice 是否是一个有效的数字
      if (!isNaN(currentNetPrice) && item.netPrice != 0) {
        // 如果找到了一个更小的 netPrice，则更新 minItem 和 minNetPrice
        if (currentNetPrice < minNetPrice) {
          // minNetPrice = currentNetPrice;
          minItem = item;
        }
      }
      // 如果 currentNetPrice 是 NaN，则不做任何操作，继续下一次循环
    }
  }
  // 返回找到的具有最小 netPrice 的对象，如果没有找到则返回 null
  return minItem;
};
//监听 当前的shuzu
// watch(selectedChannelList, (newVal, oldVal) => {
//   console.log(newVal, "newVal");
//   console.log(oldVal, "oldVal");

// });

//获取当前的选中 的channel
const getSelectedChannel = (e) => {
  selectedChannelList.value = e;
  const result = findMaxNetPriceItem(selectedChannelList.value);
  const arr = calcuteRateList(result.netPrice);
  rateList.value = arr;
  priList.value = {
    Price:
      (rateList.value[arr.length - 1]?.zhe *
        limitedPriceFun(selectedSeat.value[0].areaId)[0].price) /
      100,
    name: rateList.value[arr.length - 1]?.name,
  };
};
//计算当前选中的限价的渠道rateList 的数组
const calcuteRateList = (price) => {
  const originPrice = getOrPrice(selectedSeat.value[0].areaId) / 100;
  var minPercent = Math.ceil((price / 100 / originPrice) * 100) / 100; // 最低的比例 78%    const maxPercent = 1.0; // 最高的比例 100%
  if (
    minPercent <
    Number(
      JSON.parse(decodeURIComponent(router.params.resultInfo)).rateList[0].zhe
    )
  ) {
    minPercent = Number(
      JSON.parse(decodeURIComponent(router.params.resultInfo)).rateList[0].zhe
    );
  }
  const maxPercent = 1.0; // 最高的比例 100%
  const numberOfPercentages = 5; // 要生成的比例数量
  const generatedPercentages = generateEqualPercentages(
    minPercent,
    maxPercent,
    numberOfPercentages
  );
  return generatedPercentages;
};
//判断 当前的 选中的里面是否有支持限价的
const matchChannelFailstate = computed(() => {
  return selectedChannelList.value.some((item) => {
    return item.isSupport == 1;
  });
});
const selectedChannelList = ref([]);
// const defaultChannel = ref();

//参数说明   isSupport 是否支持限价  1 支持  0 不支持
//selectNum 主渠道 备渠道   1 主渠道   2 备渠道  默认是0 如果默认选中 可以 给当前的对象 设置1 和 0
//isGet   是否选择显示当前 渠道的 限价价格 如果 1 显示 0 不显示(直接不支持，不会获取限价)
// time 参数 是获取时间 暂不使用

const chanelList = ref([
  //渠道
  {
    id: 88,
    name: "芒果电影票",
    icon: "http://h5.liangpiao.net.cn/logo/1.jpg",
    text: "预估限价",
    isSupport: 1,
    selectNum: 1,
    time: 0,
    desc: "支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，良票平台不收取任何订单手续费",
    tip: "预估价",
    isGet: 1,
    netPrice: 0,
  },
  {
    id: 66,
    name: "芒果一口价",
    icon: "http://h5.liangpiao.net.cn/logo/1.jpg",
    text: "一口价",
    isSupport: 0,
    selectNum: 0,
    time: 0,
    desc: "你的出票成本=预估出票价",
    tip: "出票价",
    isGet: 1,
    netPrice: 0,
  },

  {
    id: 3,
    name: "麻花电影票",
    icon: "http://h5.liangpiao.net.cn/logo/maHua.jpg",
    text: "预估限价",
    isSupport: 1,
    selectNum: 0,
    time: 0,
    desc: "支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，良票平台不收取任何订单手续费",
    tip: "预估价",
    isGet: 1,
    netPrice: 0,
  },
  {
    id: 7,
    name: "守兔电影票",
    icon: "http://h5.liangpiao.net.cn/logo/2.jpg",
    text: "预估限价",
    isSupport: 1,
    selectNum: 0,
    time: 0,
    desc: "支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，良票平台不收取任何订单手续费",
    tip: "预估价",
    isGet: 0,
    netPrice: 0,
  },
  {
    id: 11,
    name: "守兔一口价",
    icon: "http://h5.liangpiao.net.cn/logo/2.jpg",
    text: "一口价",
    isSupport: 0,
    selectNum: 0,
    time: 0,
    desc: "你的出票成本=预估出票价",
    tip: "出票价",
    isGet: 1,
    netPrice: 0,
  },
  // {
  //   id: 5,
  //   name: "芒果电影票",
  //   icon: "http://h5.liangpiao.net.cn/logo/1.jpg",
  //   text: "一口价",
  //   isSupport: 0,
  //   selectNum: 0,
  //   time: 0,
  //   desc: "你的出票成本=预估出票价",
  //   tip: "出票价",
  //   isGet: 1,
  // },
  // {
  //   id: 6,
  //   name: "哈哈电影票",
  //   icon: "http://h5.liangpiao.net.cn/logo/3.jpg",
  //   text: "不支持限价",
  //   isSupport: 0,
  //   selectNum: 0,
  //   time: 0,
  //   desc: "不支持限价，你的出票成本=供应商中标价+原价*3%，手续费为供应渠道收取，票达人平台不收取任何订单手续费",
  //   tip: "预估出票价",
  //   isGet: 1,
  // },
  // {
  // 	id: 8,
  // 	name: "星驰电影票",
  // 	icon: "http://h5.liangpiao.net.cn/logo/xingChi.jpg",
  // 	text: "支持限价",
  // 	isSupport: 1,
  // 	selectNum: 0,
  // 	time: 0,
  // 	desc: "你的出票成本=预估出票价",
  // 	tip: "预估出票价",
  // 	isGet: 1,
  // },
  {
    id: 10,
    name: "影划算电影票",
    icon: "http://h5.liangpiao.net.cn/logo/ying.png",
    text: "预估限价",
    isSupport: 1,
    selectNum: 0,
    time: 0,
    desc: "支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，良票平台不收取任何订单手续费",
    tip: "预估价",
    isGet: 1,
    netPrice: 0,
  },
]);
const rateList = ref([]); // 比例
const selectedSeat = ref([]); //选中的座位
const arealist = ref([]); //区域列表
const currentShowId = ref(""); // 场次Id
const currentShowInfo = ref({}); //电影信息
const priList = ref({}); //限价数据
const screenWidth = ref(0); //页面宽度
const screenHeight = ref(0); //页面高度
// 清楚定时器
onBeforeUnmount(() => {
  stopXun.value = true;
  destroyTime();
});
const stopXun = ref(false);
//获取当前手机的信息
const getPhoneInfo = () => {
  try {
    const res = Taro.getSystemInfoSync();
    screenWidth.value = res.screenWidth;
    screenHeight.value = res.screenHeight;
  } catch (e) {
    // Do something when catch error
  }
};
//模板渲染
onMounted(async () => {
  const resultInfo = JSON.parse(decodeURIComponent(router.params.resultInfo));
  getPhoneInfo();
  Taro.showLoading({
    title: "加载中...",
    mask: true,
  });
  rateList.value = resultInfo.rateList;
  selectedSeat.value = resultInfo.selectedSeat;
  arealist.value = resultInfo.arealist;
  currentShowId.value = resultInfo.currentShowId;
  currentShowInfo.value = resultInfo.currentShowInfo;
  limitPriceInfo.value = resultInfo.rateList[2];

  for (const item of chanelList.value) {
    const params = {
      netPrice: SeatNetPrice(), //座位价格
      seatCount: selectedSeat.value.length, //座位数量
      showId: currentShowId.value, //场次Id
      seatName: backSeatName(), //座位字符串
      channel: item.id, //渠道Id
    };
    await performTask(params, item);
  }

  timerFun(function () {
    if (requestTime.value > 0) {
      requestTime.value = requestTime.value - 1;
    }
  }, 1000)();
});
//获取当前的座位价格区域
const limitedPriceFun = (str) => {
  return arealist.value.filter((item) => item.regionName == str);
};
//获取座位里的价格
const SeatNetPrice = () => {
  return limitedPriceFun(selectedSeat.value[0]?.areaId)[0]?.price;
};
//获取座位字符串数组
const backSeatName = () => {
  return selectedSeat.value.map((item) => item.seatNo);
};

let remainingTime = ref(40000);

const nList = [7, 8]; // 新接口--不调用的渠道的id
//获取当前的 渠道Id
const performTask = async (params, item) => {
  if (!nList.includes(item.id)) {
    PirceApi.GetPreQuotationSync(params).then((result) => {
      if (result.state == 200) {
        getReCall({ data: result.data.taskId }, item);
      }
    });
  } else if (item.id == 8) {
    // 单走 星驰
    PirceApi.GetPreQuotation(params).then((result) => {
      if (result.state == 200) {
        getReCall(result, item);
        // var timesRun = requestTime.value; //
        // let remainingTime = 40000; // 剩余时间，单位为毫秒
        // let callInterval = 2500; // 初始调用间隔，单位为毫秒
        // let callCount = 0; // 调用次数
        // let stopConditionMet = false; // 停止条件是否满足
        // // 递归调用的函数
        // const recursiveCall = async () => {
        // 	if (stopConditionMet || remainingTime.value <= 0) {
        // 		console.log("停止递归调用");
        // 		return; // 如果满足停止条件或剩余时间用完，则停止递归
        // 	}
        // 	callCount++;
        // 	try {
        // 		const res = await QuotationResult(result.data, item);
        // 		// 在这里处理 QuotationResult 的结果
        // 		if (res.status === 1 || res.price > 0) {
        // 			stopConditionMet = true;
        // 			return; // 停止递归调用
        // 		}
        // 		// 根据调用次数动态调整间隔（这里只是一个示例，您可以根据实际需求调整）
        // 		if (callCount > 10 && callCount <= 30) {
        // 			callInterval = 4000;
        // 		} else if (callCount > 30) {
        // 			callInterval = 5000;
        // 		}
        // 		// 更新剩余时间
        // 		remainingTime.value -= callInterval;
        // 		if (remainingTime.value < 0) {
        // 			remainingTime.value = 0; // 防止负数
        // 		}
        // 		// 设置下一次调用的超时
        // 		setTimeout(recursiveCall, callInterval);
        // 	} catch (error) {
        // 		console.error("Error in QuotationResult:", error);
        // 		// 如果需要，可以在这里停止递归调用
        // 		// stopConditionMet = true;
        // 		// 但由于您的要求是基于时间，所以这里我们不基于 QuotationResult 的结果来停止
        // 		// 仍然设置下一次调用的超时，以保持时间控制的准确性
        // 		setTimeout(recursiveCall, callInterval);
        // 	}
        // };
        // // 开始第一次调用
        // recursiveCall();
      }
    });
  }
};

// 查询预报价 公共的方法
const getReCall = (result, item) => {
  let callInterval = 2500; // 初始调用间隔，单位为毫秒
  let callCount = 0; // 调用次数
  let stopConditionMet = false; // 停止条件是否满足

  // 递归调用的函数
  const recursiveCall = async () => {
    if (stopConditionMet || remainingTime.value <= 0) {
      console.log("停止递归调用");
      return; // 如果满足停止条件或剩余时间用完，则停止递归
    }
    callCount++;
    try {
      const res = await QuotationResult(result.data, item);
      // 在这里处理 QuotationResult 的结果
      if (res.status === 1 || res.price > 0) {
        stopConditionMet = true;
        return; // 停止递归调用
      }
      // 根据调用次数动态调整间隔（这里只是一个示例，您可以根据实际需求调整）
      if (callCount > 10 && callCount <= 30) {
        callInterval = 4000;
      } else if (callCount > 30) {
        callInterval = 5000;
      }
      // 更新剩余时间
      remainingTime.value -= callInterval;
      if (remainingTime.value < 0) {
        remainingTime.value = 0; // 防止负数
      }
      // 设置下一次调用的超时
      setTimeout(recursiveCall, callInterval);
    } catch (error) {
      console.error("Error in QuotationResult:", error);
      // 如果需要，可以在这里停止递归调用
      // stopConditionMet = true;
      // 但由于您的要求是基于时间，所以这里我们不基于 QuotationResult 的结果来停止
      // 仍然设置下一次调用的超时，以保持时间控制的准确性
      setTimeout(recursiveCall, callInterval);
    }
  };
  // 开始第一次调用
  recursiveCall();
};

//获取预报价格
const QuotationResult = async (priceId, item) => {
  const result = await PirceApi.GetPreQuotationResult(priceId);
  if (result.state == 200) {
    item.netPrice = result.data.price;
    if (item.id == 88) {
      selectedChannelList.value.push(item);
      const arr = calcuteRateList(result.data.price);
      rateList.value = arr;
      priList.value = {
        Price:
          (rateList.value[arr.length - 1]?.zhe *
            limitedPriceFun(selectedSeat.value[0].areaId)[0].price) /
          100,
        name: rateList.value[arr.length - 1]?.name,
      };
      Taro.hideLoading();
    }
  }
  return { status: result.data.status, price: result.data.price };
};
//点击限价
const handleClickPrice = () => {
  limitPriceShow.value = true;
};
//点击确定选择 限价
const handleClickConfirm = () => {
  priList.value = {
    Price: PriceLimitRef.value.emitLimitPrice().limited_price,
    name: PriceLimitRef.value.emitLimitPrice().zhe,
  };
  limitPrice.value = PriceLimitRef.value.emitLimitPrice().limited_price;
  limitPriceInfo.value.zhe = PriceLimitRef.value.emitLimitPrice().zhe;
  limitPriceShow.value = false;
};

//生成比例
const generateEqualPercentages = (minPercentage, maxPercentage, count) => {
  const step = (maxPercentage - minPercentage) / (count - 1);
  const percentages = [];
  for (let i = 0; i < count - 1; i++) {
    const currentPercentage = minPercentage + step * i;
    percentages.push({
      id: i + 1,
      name: `${Math.round(currentPercentage * 100)}折`,
      zhe: currentPercentage.toFixed(2),
    });
  }
  return percentages;
};
//总数量
const totalPriceNum = computed(() => {
  // return selectedSeat.value.reduce((c1, c2) => c1 + parseFloat(c2.price), 0);
  let resPrice = 0;
  selectedSeat.value.forEach((item) => {
    const itemPrice = getOrPrice(item.areaId);
    resPrice = Number(resPrice) + Number(itemPrice);
  });
  return (resPrice / 100).toFixed(2);
});
//获取价格
const getOrPrice = (id) => {
  if (arealist.value.length === 0) {
    // 无分区
    // return Number(res.price);
  } else {
    // 有分区
    const res = arealist.value.find((item) => {
      return item.regionName == id;
    });
    return Number(res.price);
  }
};
</script>
<style lang="less">
.order-channel-container-101 {
  font-size: 24px;
  padding: 20rpx;
  padding-bottom: 100rpx;
  -webkit-overflow-scrolling: touch;
  .channel-title {
    font-size: 26px;
    color: #15181d;
    font-weight: 500;
    padding: 20px 25px;
    background-color: #fff;
    margin-top: 10px;
  }
  .set-seat-box {
    display: flex;
    padding: 20px 30px;
    align-items: center;
    justify-content: space-between;
    font-size: 24px;
    background-color: #fff;
    margin-top: 10px;
    .title {
      font-size: 26px;
      font-weight: 700;
      color: #15181d;
      display: flex;
      align-items: center;
      .text {
        margin-right: 10px;
      }
    }
    .value {
    }
  }
  .limit-prcie-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 10px 25px;
    margin-top: 10px;
    margin-bottom: 10px;
    .left {
      display: flex;
      flex-direction: column;
      .title {
        font-size: 24px;
        color: #15181d;
        font-weight: 700;
      }
      .desc {
        color: #858a99;
        font-size: 24px;
        margin-top: 10px;
      }
    }
    .right {
      .box {
        display: flex;
        padding: 15px;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        color: #eb3856;
        background-color: #fff6f7;
        border: 2px solid #f4d2da;
        border-radius: 6px;
        .price {
          font-size: 26px;
          font-weight: 700;
        }
        .rate {
          font-size: 24px;
        }
      }
    }
  }
}
</style>
